# app/routers/musics.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List

from app.schemas.music import MusicCreate, MusicResponse
from app.crud.musics import (
    create_music,
    get_music,
    get_musics,
    update_music,
    delete_music
)
from app.utils.databases import get_db
from app.utils.dependencies import get_current_user
from app.models.db_models import User

router = APIRouter(
    prefix="/musics",
    tags=["musics"],
    dependencies=[Depends(get_current_user)]
)

@router.post("/", response_model=MusicResponse)
def create_new_music(
    music: MusicCreate, 
    db: Session = Depends(get_db)
):
    return create_music(db=db, music=music)

@router.get("/", response_model=List[MusicResponse])
def read_all_musics(
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(get_db)
):
    musics = get_musics(db, skip=skip, limit=limit)
    return musics

@router.get("/{music_id}", response_model=MusicResponse)
def read_music_detail(
    music_id: int, 
    db: Session = Depends(get_db)
):
    db_music = get_music(db, music_id=music_id)
    if db_music is None:
        raise HTTPException(status_code=404, detail="音乐未找到")
    return db_music

@router.put("/{music_id}", response_model=MusicResponse)
def update_music_info(
    music_id: int, 
    music: MusicCreate,
    db: Session = Depends(get_db)
):
    db_music = update_music(db, music_id=music_id, music_data=music.dict())
    if db_music is None:
        raise HTTPException(status_code=404, detail="音乐未找到")
    return db_music

@router.delete("/{music_id}")
def remove_music(
    music_id: int, 
    db: Session = Depends(get_db)
):
    success = delete_music(db, music_id=music_id)
    if not success:
        raise HTTPException(status_code=404, detail="音乐未找到")
    return {"message": "音乐删除成功"}